import { db } from "@/db";
import { users } from "@/db/schema";
import { nanoid } from "nanoid";
import { NextResponse } from "next/server";
import { eq } from 'drizzle-orm';
export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { username, email, password } = body;

    // 验证请求数据
    if (!username || !email || !password) {
      return NextResponse.json(
        { message: "用户名、邮箱和密码都是必填项" },
        { status: 400 }
      );
    }

    // 检查用户名是否已存在
    const existingUserByUsername = await db.select()
      .from(users)
      .where(eq(users.username, username))
      .limit(1);
    if (existingUserByUsername && existingUserByUsername.length > 0) {
      return NextResponse.json(
        { message: "用户名已被使用" },
        { status: 409 }
      );
    }

 
    const existingUserByEmail = await db.select()
    .from(users)
    .where(eq(users.email, email))
    .limit(1);

    if (existingUserByEmail && existingUserByEmail.length > 0) {
      return NextResponse.json(
        { message: "邮箱已被注册" },
        { status: 409 }
      );
    }

    // 创建新用户
    // 注意：在生产环境中，应该对密码进行哈希处理
    const userId = nanoid();
    await db.insert(users).values({
      id: userId,
      username,
      email,
      password, // 实际应用中应该使用哈希密码
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    return NextResponse.json(
      { message: "用户注册成功", userId },
      { status: 200 }
    );
  } catch (error) {
    console.error("注册错误:", error);
    return NextResponse.json(
      { message: "注册过程中发生错误" },
      { status: 500 }
    );
  }
}